package com.intelligent.health.base.controller;

import com.intelligent.health.base.excption.EmailSendException;
import com.intelligent.health.base.service.email.impl.SendEmailServiceImpl;
import entity.*;
import entity.constant.ExceptionConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: torlesse-liang
 * @Date: 2022/04/05/10:44
 * @Description: 邮件发送
 */
@Slf4j
@RestController
@RequestMapping("/email")
public class EmailSendController {

    /**
     * 邮件发送者
     */
    @Value(value = "${spring.mail.username}")
    private String fromEmail;

    @Autowired
    private SendEmailServiceImpl sendEmailService;

    /**
     * 发送邮件
     *
     * @param emailInfo 邮件信息
     * @throws EmailSendException 邮件发送异常
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    @PostMapping("/send/{action}")
    public R sendSimpleMail(@PathVariable("action") String action, @RequestBody EmailInfo emailInfo) throws EmailSendException {
        emailInfo.setFromEmail(fromEmail);
        try {
            sendEmailService.emailSend(action, emailInfo);
        } catch (Exception e) {
            log.error("邮件发送失败: {}", emailInfo);
            throw new EmailSendException(ExceptionConst.EMAIL_SEND_ERROR);
        }
        log.info("邮件发送成功: {}", emailInfo);
        return R.setResult(ResultCodeEnum.EMAIL_SEND_SUCCESS);
    }

}